/*
 * Copyright 2011-2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0.
 * See `LICENSE` in the project root for license information.
 */

package me.ijleex.platform.system.admin.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import me.ijleex.platform.core.util.MathUtils;
import me.ijleex.platform.framework.constant.Constants;
import me.ijleex.platform.framework.entity.Result;
import me.ijleex.platform.system.admin.entity.Admin;
import me.ijleex.platform.system.admin.entity.AdminRole;
import me.ijleex.platform.system.admin.mapper.AdminMapper;
import me.ijleex.platform.system.admin.mapper.AdminRoleMapper;
import me.ijleex.platform.system.admin.service.IAdminRoleService;

/**
 * 管理员&角色关系 服务层实现
 *
 * @author liym
 * @since 2019-03-14 11:43:16 By 'codegen'
 */
@Service
public class AdminRoleServiceImpl implements IAdminRoleService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private final AdminRoleMapper mapper;
    private final AdminMapper adminMapper;

    public AdminRoleServiceImpl(AdminRoleMapper mapper, AdminMapper adminMapper) {
        this.mapper = mapper;
        this.adminMapper = adminMapper;
    }

    @Override
    public List<Long> getRoleIdByAdminId(Long adminId) {
        return this.mapper.selectRoleIdByAdminId(adminId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result grant(AdminRole object) {
        Long adminId = object.getAdminId();
        if (MathUtils.isNullOrZero(adminId)) {
            return Result.invalidArg("管理员编号不能为空：adminId");
        }
        logger.debug("为管理员【{}】分配角色", adminId);

        Admin admin = this.adminMapper.selectById(adminId);
        if (admin == null) {
            return Result.error("管理员不存在：" + adminId);
        }

        String roleIds = object.getRoleIds();
        if (StringUtils.isBlank(roleIds)) {
            // 如果角色id为空，则删除已分配的角色

            logger.warn("为管理员分配角色时，待分配的角色为空，将删除管理员原有的角色");
            int x = this.mapper.deleteByAdminId(adminId);
            if (x == 0) {
                return Result.error("删除管理员已有的角色失败：" + adminId);
            } else {
                // TODO 清除缓存
                return Result.ok(adminId);
            }
        } else {
            logger.debug("为管理员分配角色，先删除管理员原有的角色");

            // 授权之前，删除以前授权的数据
            this.mapper.deleteByAdminId(adminId);

            String[] roleIdArr = roleIds.split(Constants.DELIMITER);
            try {
                int count = 0;
                for (String roleId : roleIdArr) {
                    object.setRoleId(Long.parseLong(roleId));
                    // 设置 remarks 的值为管理员名，方便删除时使用
                    object.setRemarks(admin.getLoginId());
                    count += this.mapper.insert(object);
                }
                return Result.ok("为管理员分配角色成功：" + adminId + "，角色个数：" + count);
            } catch (Exception e) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                logger.error("为管理员分配角色失败", e);
                return Result.error("管理员授权失败");
            }
        }
    }

}
